//https://leetcode.cn/problems/target-sum/
package codeRandomThoughts.Test494目标和;

public class Solution2 {
    public int findTargetSumWays(int[] nums, int target) {
        //求数组总和
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }


        if ((target + sum) % 2 == 1) return 0;
        if (Math.abs(target) > sum) return 0;//全部都一个符号也构造不了
        int positiveSum = (target + sum) / 2;

        //dp[j]:从0-i的数组中任取元素,使得和恰好为j的方法数为dp[i][j]
        int[] dp = new int[positiveSum + 1];

        //初始化
        dp[nums[0]] = 1;

        for (int i = 0; i < nums.length; i++) {
            for (int j = positiveSum; j >= nums[i]; j--) {
                dp[j] += dp[j - nums[i]];
            }
        }


        return dp[positiveSum];
    }
}
